<template>
  <!-- <div @click="aaaa">aaaaaaa</div> -->
  <div class="product_settings">
    <div class="product_pool">
      <div class="title"><b>产品池列表</b></div>
      <ul id="pool_type" class="pool_type">
        <li v-for="item in poolData.value" :key="item.tempId"
          :class="{active : curPool.value ? item.tempId == curPool.value.tempId : true}" @click="switchPool(item)">
          <div class="pool_li">
            <span>{{item.poolTitle}}池</span>
            <el-icon class="move" :size="18" v-if="!readOnly && !modify">
              <Rank />
            </el-icon>
          </div>

          <div class="del" @click.stop="delPool(item.tempId)" v-if="!readOnly && !modify">
            <el-icon>
              <Close />
            </el-icon>
          </div>
        </li>
      </ul>
      <div class="dashed_but" @click="openBusiType" v-if="!readOnly && !modify">
        <el-icon>
          <Plus />
        </el-icon>
        <span>添加产品池</span>
      </div>
    </div>
    <div class="pool_details_layout" v-if="curPool.value">
      <div class="pool_details_title">
        <span class="details_title_span">产品池名称：</span>
        <el-input class="details_title_input" v-model="curPool.value.giftPoolName" placeholder="请输入"
          :clearable="true" :disabled="readOnly || modify" />
        <span class="details_title_span">可兑换产品数量：</span>
        <el-input-number v-model="curPool.value.maxExchangeNum" :min="1" :disabled="readOnly || modify" class="margin_left" />
      </div>
      <DynamicParams ref="productPoolRef" :data="curPool.value.detailItems" :template="template" typeProp="detailType" :showDefault="false"
        :customAdd="true" @add="add" :operation=poolOperation()>
        <el-table-column label="产品图片" width="105">
          <template #default="scope">
            <img :src="scope.row.mainPic" :style="{
              width: '75px',
              height: '75px',
            }" />
          </template>
        </el-table-column>
        <el-table-column label="产品名称" prop="name"></el-table-column>
        <el-table-column label="产品编号" prop="code"></el-table-column>
        <el-table-column label="产品类型" prop="category"></el-table-column>
      </DynamicParams>
    </div>

    <el-dialog v-model="dialogVisible" title="选择" width="35%" top="35vh" class="base_dialog">
      <el-form ref="busiTypeFormRef" :model="busiTypeForm" :rules="trafficRules">
        <el-form-item label="池类型" prop="type">
          <el-radio-group v-model="busiTypeForm.type">
            <el-radio label="1003001">商品</el-radio>
            <el-radio label="1003002">旅行</el-radio>
            <el-radio label="1003003">酒店</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <el-drawer v-model="drawer" title="添加产品" direction="rtl" :close-on-click-modal="false" :size="720"
      custom-class="base_drawer">
      <ProductTable type="add" ref="addTableRef" :typeKey="typeKey"></ProductTable>
      <template #footer>
        <div>
          <el-button @click="closeDrawer">取消</el-button>
          <el-button @click="saveProduct" type="primary">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import DynamicParams from "@com/DynamicParams.vue";
import ProductTable from "@com/marketing/ProductTable.vue";
import { defineProps, reactive, ref, defineExpose, onMounted, watch } from "vue";
import Sortable from 'sortablejs';
import $ from "@util/base"
import { $msg } from "@/common/ui/msg";
import api from "@api/productChoose";

const props = defineProps({
  data: { type: Array, default: () => [] },
  readOnly: { type: Boolean, default: false },
  travelProgramme: { type: Array },
  modify: { type: Boolean, default: false }
})

function aaaa() {
  console.log(getValue())
}

function poolOperation() {
  if (props.readOnly) {
    return {
      move: false,
      modify: false,
      del: false,
      add: false,
      check: false,
    }
  } else {
    return {
      move: !props.modify,
      modify: false,
      del: !props.modify,
      add: !props.modify,
      check: false,
    }
  }
}

const template = {
  detailType: null, detailTitle: null, startTime: null, hotelItems: props.travelProgramme
}

watch(() => props.data, val => {
  poolData.value = initData()
  sortData.value = poolData.value
  if ($.isNotEmpty(poolData.value)) {
    curPool.value = val[0]
    lastPool = val[0]
  }
})

watch(() => props.travelProgramme, val => {
  template.hotelItems = $.deepCopy(val)
})

const poolData = reactive({ value: initData() })

function initData() {
  if ($.isNotEmpty(props.data)) {
    return props.data.map((e) => {
      e.tempId = $.uuid8()
      e.poolTitle = TYPE[e.busiType].title
      e.poolValue = TYPE[e.busiType].val
      api.chooseList(TYPE[e.busiType].val, {
        codeList: e.codeList,
      },
        (val) => {
          e.detailItems = val.itemList;
        }
      );
      return e
    })
  } else {
    return []
  }
}

const TYPE = {
  1003001: {
    title: '商品',
    val: 'goods'
  },
  1003002: {
    title: '旅行',
    val: 'travel'
  },
  1003003: {
    title: '酒店',
    val: 'hotel'
  }
}

// if ($.isEmpty(props.data)) {
//   for (let i in TYPE) {
//     let template = {
//       giftPoolName: null,
//       maxExchangeNum: null,
//       busiType: i,
//       poolTitle: TYPE[i].title,
//       poolValue: TYPE[i].val,
//       tempId: $.uuid8(),
//       detailItems: []
//     }
//     poolData.value.push(template)
//   }
// }

function delPool(id) {
  poolData.value.remove((e) => { return e.tempId === id })
  if (id == curPool.value.tempId) {
    if (poolData.value.length > 0) {
      curPool.value = poolData.value[0]
    } else {
      curPool.value = []
    }
  }
}

function openBusiType() {
  dialogVisible.value = true
  resetForm()
}

function addRouteDay(busiType) {
  let template = {
    giftPoolName: null,
    maxExchangeNum: 1,
    busiType: busiType,
    poolTitle: TYPE[busiType].title,
    poolValue: TYPE[busiType].val,
    tempId: $.uuid8(),
    detailItems: []
  }

  poolData.value.push(template)
  if (poolData.value.length == 1) {
    curPool.value = poolData.value[0]
    lastPool = poolData.value[0]
  }
}

const dialogVisible = ref(false)
const busiTypeFormRef = ref('')
const busiTypeForm = reactive({
  type: '',
})
const trafficRules = {
  type: [{
    required: true,
    message: '请选择池类型',
    trigger: 'change',
  }],
}
const submitForm = () => {
  busiTypeFormRef.value.validate((valid) => {
    if (valid) {
      addRouteDay(busiTypeForm.type)
      dialogVisible.value = false
      // let index = poolData.value.findIndex( e => e.busiType == busiTypeForm.type)
      // if (index < 0) {
      //   addRouteDay(busiTypeForm.type)
      //   dialogVisible.value = false
      // } else {
      //   $msg.error(`已存在${TYPE[busiTypeForm.type].title}池`)
      // }
    }
  })
}

const resetForm = () => {
  if (!busiTypeFormRef.value) return
  busiTypeFormRef.value.resetFields()
}

const productPoolRef = ref(null)
const curPool = reactive({ value: null })
var lastPool = null

function switchPool(data) {
  if (data.tempId != curPool.value.tempId) {
    curPool.value.detailItems = productPoolRef.value.getValue()
    let routeDetails = curPool.value.detailItems;
    //routeDetails数据保存在池中
    lastPool.detailItems = routeDetails
    //切换当前池
    curPool.value = data
    //记录上次池
    lastPool = data
  }
}

function checkData(list) {
  let s = []
  for (let i = 0; i < list.length; i++) {
    if (check(list[i], list[i].detailItems)) {
      s.push(true)
    } else {
      s.push(false)
    }
  }
  return s.every(e => {
    return e
  })
}

function check(day, routeDetails) {
  if ($.isEmpty(day.giftPoolName)) {
    $msg.error("请填写" + day.poolTitle + "池名称")
    return false
  }
  if ($.isEmpty(day.maxExchangeNum)) {
    $msg.error("请填写" + day.poolTitle + "池兑换产品数量")
    return false
  }
  if (day.maxExchangeNum > routeDetails.length) {
    $msg.error(day.poolTitle + "池兑换产品数量不能大于池内数量")
    return false
  }
  if ($.isEmpty(routeDetails)) {
    $msg.error("请设置" + day.poolTitle + "池产品详情")
    return false
  }
  return true
}

const sortData = reactive({ value: poolData.value });
onMounted(() => {
  if (!props.readOnly) {
    const ul = document.querySelector('#pool_type')
    Sortable.create(ul, {
      handle: ".move",
      animation: 150,
      onEnd: function (evt) {
        const currRow = sortData.value.splice(evt.oldIndex, 1)[0];
        sortData.value.splice(evt.newIndex, 0, currRow);
      }
    })
  }
})

function handerData(poolData) {
  for (const day of poolData) {
    day.codeList = day.detailItems.map(item => { return item.code })
    delete day.tempId
    delete day.poolTitle
    delete day.poolValue
    delete day.detailItems
  }
  return poolData
}

function getValue() {
  if (checkData(poolData.value)) {
    return handerData($.deepCopy(poolData.value))
  } else {
    return false
  }
}

function add() {
  openDrawer()
  if (!addTableRef.value) return
  addTableRef.value.clearSelection()
}

const drawer = ref(false)
const typeKey = ref(null)
const addTableRef = ref(null);

function openDrawer() {
  typeKey.value = curPool.value.poolValue
  drawer.value = true
}
function closeDrawer() {
  drawer.value = false;
}
function saveProduct() {
  let data = addTableRef.value.getSelectData();
  if ($.isEmpty(data)) {
    $msg.error("请勾选需要添加的产品");
  } else {
    // curPool.value.detailItems = data
    let newData = [...productPoolRef.value.getValue(),...data]
    let map = new Map();
    for(let item of newData){
      if(!map.has(item.code)){
        map.set(item.code, item)
      }
    }
    let newArr = [...map.values()];
    curPool.value.detailItems = newArr
    closeDrawer();
  }
}

defineExpose({ getValue })
</script>
<style lang="scss">
.product_settings {
  display: flex;
  border: 1px solid $border;

  .product_pool {
    display: flex;
    flex-direction: column;
    width: 180px;
    border-right: 1px solid $border;

    .active {
      background-color: $primary;
      color: #fff;
    }

    ul {
      list-style-type: none;
    }

    ul>li {
      color: #333;
      cursor: pointer;
      padding: 10px;
      margin: 10px;
      background-color: #f1f1f1;
      position: relative;
      border-radius: 2px;

      &:hover {
        .del {
          display: block;
        }
      }
    }

    .pool_li {
      display: flex;
      align-items: center;
      padding-right: 10px;
      justify-content: space-between;
    }

    .del {
      display: none;
      cursor: pointer;
      top: -6px;
      right: -6px;
      background-color: #fc443e;
      color: #fff;
      position: absolute;
      width: 20px;
      height: 20px;
      line-height: 26px;
      text-align: center;
      border-radius: 50%;
    }

    .dashed_but {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 5px;

      span {
        margin-left: 2px;
      }
    }
  }

  .title {
    width: 100%;
    text-align: center;
    height: 55px;
    padding: 0;
    line-height: 55px;
    border-bottom: 1px solid $border;
    margin-bottom: 15px;
  }

  .pool_details_layout {
    padding: 0 20px;
    width: 100%;

    .pool_details_title {
      display: flex;
      align-items: center;
      height: 55px;

      b {
        margin-right: 10px;
      }
      .details_title_span {
        color: #606266;
        font-size: 14px;
        &::before {
          content: "*";
          color: #f56c6c;
          margin-right: 4px;
        }
      }

      .details_title_input {
        width: 150px;
        margin-right: 10px;
      }

      .margin_left {
        margin-left: 10px;
      }
    }

    .el-input__inner {
      width: 60px;
    }
  }

  .m_b_10 {
    margin-bottom: 10px;
  }


  .travel_programme {
    text-align: left;

    margin-top: 10px;
  }

  .programme_room {
    margin-top: 5px;
    padding: 6px 8px;
    background-color: #f2f2f2;
    display: flex;
    justify-content: space-between;
  }
}
</style>